package com.tensquare.article.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import com.tensquare.article.repository.CommentRepository;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import com.tensquare.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;

@Service
public class ArticleService {

    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private IdWorker idWorker;

    public List<Article> findAll() {
         return articleDao.selectList(null);
    }

    public Page<Article> findByPage(Integer pageNum, Integer pageSize, Map<String, Object> map) {

        //设置查询条件
        EntityWrapper<Article> entityWrapper = new EntityWrapper();
        for(String key:map.keySet()){
            entityWrapper.eq(null!=map.get(key),key,map.get(key));
        }

        //设置分页参数
        Page<Article> page = new Page<Article>(pageNum,pageSize);

        //执行查询,第一个是分页参数，第二个是查询条件
        List<Article> articles = articleDao.selectPage(page, entityWrapper);
        page.setRecords(articles);
        return page;

    }

    public void save(Article article) {
        //生成分布式ID
        String id = idWorker.nextId()+"";
        article.setId(id);
        //初始化参数
        article.setVisits(0); //浏览量
        article.setComment(0); //评论数
        article.setThumbup(0); //点赞数

        articleDao.insert(article);

    }


    public void deleteById(String id) {
        articleDao.deleteById(id);
    }

    public int update(Article article) {
        EntityWrapper<Article> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("id",article.getId());
        return articleDao.update(article,entityWrapper);
    }
}
